package ChanSyncObj

import (
	"sync"
	"time"
)

/**
说明：多线程之间，基于go的chan实现的简单消息等待/通知机制
*/

var (
	syncMap sync.Map
)

func Instance(key string) {
	ch, ok := syncMap.Load(key)
	if ok {
		return
	}

	ch = make(chan interface{}, 1)
	syncMap.Store(key, ch)
}

func Release(key string) {
	ch, ok := syncMap.Load(key)
	if !ok {
		return
	}

	close(ch.(chan interface{}))
	syncMap.Delete(key)
}

func SimpleWait(uuid string, timeout int64) interface{} {
	Instance(uuid)
	data := Wait(uuid, timeout)
	Release(uuid)

	return data
}

func Wait(key string, timeout int64) interface{} {
	val, ok := syncMap.Load(key)
	if !ok {
		return nil
	}

	ch := val.(chan interface{})

	select {
	case data := <-ch:
		return data
	case <-time.After(time.Duration(timeout) * time.Millisecond):
		return nil
	}
}

func Notify(key string, data interface{}) {
	val, ok := syncMap.Load(key)
	if !ok {
		return
	}
	ch := val.(chan interface{})

	ch <- data
}
